#include "lrcwidget.h"
#include "ui_lrcwidget.h"
#include <QDebug>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
LrcWidget::LrcWidget(QWidget *parent) :
    QWidget(parent),
    _manager(new QNetworkAccessManager(this)),
    ui(new Ui::LrcWidget)
{
    ui->setupUi(this);
}

LrcWidget::~LrcWidget()
{
    delete ui;
}

void LrcWidget::updateCurUrl(const QUrl &url)
{
    qDebug() << "_currentUrl: " << _currentUrl << " ,  url: " << url;
    if(_currentUrl == url) return;
    _currentUrl = url;
    _lyric.clear();

    qint64 id = SongManager::instance()->getSongItem(url).wangyiyun_id;
    qDebug() << "当前播放歌曲的网易云id:" << id;
    if (id == 0){// 本地, 先搜索单曲, 根据id再搜索歌词
        const SongItem& song = SongManager::instance()->getSongItem(url);
        QString urlStr = "https://music.163.com/api/search/get/web?s=" + song.name + ' ' + song.artist + "&type=1&limit=1&offset=0";
        qDebug() << "开始找本地音乐" << song.name << "-" << song.artist << "的网易云id";
        QNetworkRequest request;
        request.setUrl(urlStr);
        QNetworkReply* reply = _manager->get(request);
        connect(reply, &QNetworkReply::finished, this, [=](){
            if(reply->error() != QNetworkReply::NoError){
                qDebug() << "请求出错: " << reply->errorString();
                reply->deleteLater();
                return;
            }
            QByteArray rawData = reply->readAll();
            qDebug() << QString(rawData);
            qint64 id = QJsonDocument::fromJson(rawData).object().value("result").toObject().value("songs").toArray()[0].toObject().value("id").toVariant().toLongLong();
            if(id){
                qDebug() << "找到了本地音乐" << song.name << "-" << song.artist << "的网易云id:" << id;
                SongItem updatedSong = song;
                updatedSong.wangyiyun_url = "http://music.163.com/song/media/outer/url?id=" + QString::number(id) + ".mp3";
                updatedSong.wangyiyun_id = id;
                SongManager::instance()->addSongItem(updatedSong);
                _currentUrl.clear();
                updateCurUrl(song.url());
            }else {
                qDebug() << "没找到本地音乐" << song.name << "-" << song.artist << "的网易云id";
            }
        });
    } else {
        QString urlStr = "https://music.163.com/api/song/lyric?id=" + QString::number(id) + "&lv=1&kv=1&tv=1";
        // "{\"sgc\":false,\"sfy\":false,\"qfy\":false,\"lrc\":{\"version\":7,\"lyric\":\"[00:00.000] 作词 : TetraCalyx\\n[00:00.048] 作曲 : 蔡近翰Zoe(HOYO-MiX)\\n[00:00.096] 编曲 : 宫奇Gon(HOYO-MiX)/苑迪萌Dimeng Yuan(HOYO-MiX)/崔瀚普TSAR(HOYO-MiX)/车子玉Ziyu Che(HOYO-MiX)\\n[00:00.144] 制作人 : 蔡近翰Zoe(HOYO-MiX)\\n[00:00.195]When good old friends are going away\\n[00:06.838]Will you wish them to remember your name?\\n[00:13.480]When good old days are passing away\\n[00:19.851]Will you promise your heart remains the same\\n[00:27.289]Never can we suspend the time\\n[00:33.943]Having to leave the tracks behind\\n[00:40.316]there is a longer way ahead, After all.\\n[00:54.403]There used to be a story teller\\n[01:00.242]who always painted the sunshine and the rain\\n[01:07.428]One has to eventually grow up\\n[01:13.258]Spending a lifetime to taste the love and pain\\n[01:20.705]Never can we suspend the time\\n[01:27.345]Having to leave the tracks behind\\n[01:33.718]there is a longer way ahead, After all.\\n[01:47.005]If it’s too hard to say goodbye\\n[01:53.372]Give us a try to sing a rhyme\\n[01:59.768]“May you, the beauty of this world, always shine.”\\n[02:13.309]\\n[02:14.309] 演唱 Vocal Artist：车子玉Ziyu Che(HOYO-MiX)\\n[02:14.356] 弦乐 Strings：龙之艺交响乐团Art of Loong Orchestra\\n[02:14.403] 弦乐录音棚 Strings Recording Studio：上海音像公司录音棚YX STUDIO\\n[02:14.450] 混音 Mixing Engineer：宫奇Gon(HOYO-MiX)\\n[02:14.497] 母带 Mastering Engineer：宫奇Gon(HOYO-MiX)\\n[02:14.544] 出品 Produced by：HOYO-MiX\\n\"},\"klyric\":{\"version\":0,\"lyric\":\"\"},\"tlyric\":{\"version\":5,\"lyric\":\"\\n[00:00.195]当曾经的挚友离开\\n[00:06.838]你是否期待他们能牢记你姓名\\n[00:13.480]当美好的旧日远去\\n[00:19.851]你的心是否仍旧如初?\\n[00:27.289]我们无法停止时间\\n[00:33.943]只得将车辙留在身后\\n[00:40.316]毕竟前方的道路更长\\n[00:54.403]曾有个故事的讲述者\\n[01:00.242]描绘着阳光雨露\\n[01:07.428]而人终究要长大\\n[01:13.258]用毕生时光去体会爱与伤痛\\n[01:20.705]我们无法停止时间\\n[01:27.345]只得将车辙留在身后\\n[01:33.718]毕竟前方的道路更长\\n[01:47.005]如果难以说出再见\\n[01:53.372]那让我们试着唱出来\\n[01:59.768]“你便是世界上的美好，永远闪耀。”\\n[02:13.309]\\n\"},\"code\":200}"
        QNetworkRequest request;
        request.setUrl(QUrl(urlStr));
        QNetworkReply* reply = _manager->get(request);
        connect(reply, &QNetworkReply::finished, this, [=](){
            if(reply->error() != QNetworkReply::NoError){
                qDebug() << "请求出错: " << reply->errorString();
                reply->deleteLater();
                return;
            }
//            qDebug() << QString(reply->readAll());
            QByteArray rawData = reply->readAll();
            QString ret = QJsonDocument::fromJson(rawData).object().value("lrc").toObject().value("lyric").toString();
//            qDebug() << text;
            // 按换行符分割成单行
            QStringList lines = ret.split("\n", QString::SkipEmptyParts);
            for(auto line : lines){ // 对每行提取时间 + 内容
                int min, sec, ms;
                sscanf(line.toStdString().c_str(), "[%d:%d.%d]", &min, &sec, &ms);
                line.remove(0, line.lastIndexOf(']') + 1);
                if(line.isEmpty()) continue;
                qDebug() << min << sec << ms << line;
                qint64 duration = min * 60 * 1000 + sec * 1000 + ms;
                _lyric.push_back({duration, line});
            }
        });
    }
}

void LrcWidget::updateCurDuration(qint64 duration)
{
    int index = getIndexOf(duration);
    ui->label_1->setText(getText(index - 2));
    ui->label_2->setText(getText(index - 1));
    ui->label_3->setText(getText(index - 0));
    ui->label_4->setText(getText(index + 1));
    ui->label_5->setText(getText(index + 2));
    ui->label_6->setText(getText(index + 3));
    ui->label_7->setText(getText(index + 4));
    ui->label_8->setText(getText(index + 5));
    ui->label_9->setText(getText(index + 6));
}

int LrcWidget::getIndexOf(qint64 duration)
{
    int ret = -1;
    // TODO: 改成二分
    while(ret + 1 < _lyric.size() && duration >= _lyric[ret + 1].time){
        ret++;
    }
    return ret;
}

QString LrcWidget::getText(int index)
{
    if(index < 0 || index >= _lyric.size()) return "";
    else return _lyric[index].text;
}
